package file

import (
	"ZHONGYIHANGYAN/util/log"
	"encoding/json"
	"os"
	"sync"
)

var logErr, logInfo = log.GetLogger("file")

// 读取JSON文件
func ReadFromJson(path string, v interface{}, lock *sync.RWMutex) {
	if lock != nil {
		lock.RLock()
		defer lock.RUnlock()
	}

	if file, err := os.Open(path); err != nil {
		logErr.Printf("读取%s文件出错: %v", path, err)
	} else {
		defer file.Close()
		decoder := json.NewDecoder(file)
		decoder.Decode(&v)
	}

}

// 写入JSON文件
func WriteToJson(path string, v interface{}, lock *sync.RWMutex) {
	logErr.Printf("开始写json数据%s", path)
	if lock != nil {
		lock.Lock()
		defer lock.Unlock()
	}

	if file, err := os.Create(path); err != nil {
		logErr.Printf("写入%s文件出错: %v", path, err)
	} else {
		defer file.Close()
		e := json.NewEncoder(file)
		e.SetIndent("", "    ") // 设置4个空格缩进，保持JSON格式化
		e.Encode(v)
	}

}
